//
//  YXJCVC.m
//  Tunnel
//
//  Created by wbb on 2025/6/14.
//

#import "YXJCVC.h"
#import "YXJCCell.h"
#import "YXJCDetailVC.h"
#import "CascadePickerView.h"
#import "MJRefresh/MJRefresh.h"
#import "YXJCModel.h"
#import "BRTextPickerView.h"
#import "SearchView.h"
#import "TYBaseNavigationController.h"

@interface YXJCVC ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) NSMutableArray * dataArr;
@property (nonatomic, strong) TYBaseTableView * tableView;
@property (nonatomic) NSInteger  page;
@property (nonatomic,copy) NSString*  direction;
@property (nonatomic,copy) NSString*  devName;
//@property (nonatomic,copy) NSString*  onOffStatus;
@property (nonatomic,strong) CascadePickerView *pickerView;
@property (nonatomic,strong) UIButton *btn1;
@property (nonatomic,strong) UIButton *btn2;
@property (nonatomic,strong) UIButton *btn3;
@property (nonatomic,strong) NSArray *systemDictionaryList;
@property (nonatomic,strong) NSArray *bodyDictionarylist;
@property (nonatomic,copy) NSString *systemDictionaryId;
@property (nonatomic, copy) NSString * searchContent; // 搜索文本

@end

@implementation YXJCVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"运行监测";
    self.page = 1;
    self.dataArr = [NSMutableArray array];
    self.direction = @"";
    self.searchContent = @"";
    [self initUI];
    
    self.onOffStatus =  self.onOffStatus?:@"";

    kWEAK_SELF
    [TYNetWorkTool postRequest:TYPostSystemDictionaryList
                    parameters:@{@"levelType":@"巡检",@"planDictionaryId":@"6",@"proId":@"1"}
                  successBlock:^(BOOL success, id  _Nonnull data, NSString * _Nonnull msg) {
        weakSelf.systemDictionaryList = data[@"data"];
        if(weakSelf.systemDictionaryList.count > 0){
            NSDictionary * dict =  weakSelf.systemDictionaryList[0];
            weakSelf.systemDictionaryId = dict[@"id"];
            [weakSelf loadBodyDictionaryReq];
        }
        
        
    } failureBlock:^(NSString * _Nonnull description) {
        
    }];

    if(![WDGlobal shareInstance].isNeedSarch) {
        UIBarButtonItem *right1 = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"nav_search"] style:UIBarButtonItemStylePlain target:self action:@selector(search)];
        right1.tintColor = hexColor(2A2A2A);
        self.navigationItem.rightBarButtonItems   = @[right1];

    }
}
-(void)search{
    [WDGlobal shareInstance].isNeedSarch = YES;
    
    YXJCVC *vc = [[YXJCVC alloc] init];
    TYBaseNavigationController *nav = [[TYBaseNavigationController alloc] initWithRootViewController:vc];
    
    [self presentViewController:nav animated:YES completion:^{
        nav.interactivePopGestureRecognizer.enabled = NO;
    }];
}

- (void)setOnOffStatus:(NSString *)onOffStatus {
    _onOffStatus = onOffStatus;
    NSString *title = @"设备状态";
    if([onOffStatus isEqualToString:@"0"]){
        title = @"离线";
    }else if ([onOffStatus isEqualToString:@"1"]) {
        title = @"在线";
    }
    [self.btn3 setTitle:title forState:UIControlStateNormal];

}
-(void)loadBodyDictionaryReq{
    
    kWEAK_SELF
    [TYNetWorkTool postRequest:TYPostBodyDictionaryList
                    parameters:@{@"levelType":@"巡检",@"systemDictionaryId":weakSelf.systemDictionaryId,@"proId":@"1"}
                  successBlock:^(BOOL success, id  _Nonnull data, NSString * _Nonnull msg) {
        weakSelf.bodyDictionarylist = data[@"data"];
     
    } failureBlock:^(NSString * _Nonnull description) {
        
    }];

}
- (void)initUI {
    SearchView *searchView = [[SearchView alloc] initWithTitle:@"设备编号"];
    kWEAK_SELF;
    // 搜索事件回调
    searchView.searchBlock = ^(NSString * _Nonnull content) {
        weakSelf.searchContent = content;
        [weakSelf initRequest];
    };
    
    UIView *topView = [[UIView alloc] init];
    [self.view addSubview:topView];
   
    
    if([WDGlobal shareInstance].isNeedSarch){
        [self.view addSubview:searchView];
        [searchView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
            make.left.right.offset(0);
            make.height.offset(40);
        }];
        
        [topView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.offset(0);
            make.height.offset(50);
            make.top.equalTo(searchView.mas_bottom);

        }];
    }else {
        [topView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.offset(0);
            make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
            make.height.offset(50);
        }];
    }
    
    
    UIButton *btn1 = [UIButton buttonWithTitle:@"设备类型" titleColor:main_light_text_color_6 font:[UIFont systemFontOfSize:14] imageName:@"select_icon"  target:self action:@selector(onType:)];
    btn1.tag = 10;
    [topView addSubview:btn1];
    self.btn1 = btn1;
    UIButton *btn2 = [UIButton buttonWithTitle:@"设备方向" titleColor:main_light_text_color_6 font:[UIFont systemFontOfSize:14] imageName:@"select_icon"  target:self action:@selector(onType:)];
    btn2.tag = 11;
    [topView addSubview:btn2];
    self.btn2 = btn2;
    
    UIButton *btn3 = [UIButton buttonWithTitle:@"设备状态" titleColor:main_light_text_color_6 font:[UIFont systemFontOfSize:14] imageName:@"select_icon"  target:self action:@selector(onType:)];
    btn3.tag = 12;
    [topView addSubview:btn3];
    self.btn3 = btn3;
    
    [btn1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.offset(0);
        
    }];
    
    [btn3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.right.bottom.offset(0);
        
    }];
    
    [btn2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.offset(0);
        make.left.equalTo(btn1.mas_right);
        make.right.equalTo(btn3.mas_left);
        make.width.equalTo(btn1.mas_width);
        make.width.equalTo(btn3.mas_width);

    }];
    
    [btn1 layoutButtonWithEdgeInsetsStyle:TYButtonEdgeInsetsStyleRight imageTitleSpace:5];
    [btn2 layoutButtonWithEdgeInsetsStyle:TYButtonEdgeInsetsStyleRight imageTitleSpace:5];
    [btn3 layoutButtonWithEdgeInsetsStyle:TYButtonEdgeInsetsStyleRight imageTitleSpace:5];
    
    
    
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(topView.mas_bottom);
        make.left.right.offset(0);
        make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
    }];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.page = 1;
        [weakSelf initRequest];
    }];
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.page ++;
        [weakSelf initRequest];
    }];
    [footer setTitle:@"没有更多了" forState:MJRefreshStateNoMoreData];
    self.tableView.mj_footer = footer;
    [self.tableView.mj_header beginRefreshing];

}
-(void)initRequest{
    kWEAK_SELF;
    [TYNetWorkTool postRequest:TYGetPaing parameters:@{
        @"direction":weakSelf.direction,
        @"onOffStatus":weakSelf.onOffStatus,
        @"devName":weakSelf.devName?:@"",
        @"pageNum": @(weakSelf.page),
        @"pageSize": @20,
        @"id":weakSelf.searchContent?:@""
      } successBlock:^(BOOL success, id  _Nonnull data, NSString * _Nonnull msg) {
        // 进入DispatchGroup，表示开始一个任务
        NSLog(@"-------1111-----------");
        if(success) {
            if(self.page == 1){
                [weakSelf.dataArr removeAllObjects];
            }
            
           [weakSelf.dataArr addObjectsFromArray:[NSArray yy_modelArrayWithClass:YXJCModel.class json:data[@"data"][@"list"]]];
            [weakSelf.tableView cyl_reloadData];
            self.hasNextPage =  [data[@"data"][@"hasNextPage"] boolValue];

            
        }
        [weakSelf.tableView.mj_header endRefreshing];
        if(weakSelf.hasNextPage){
            [weakSelf.tableView.mj_footer endRefreshing];
        }else{
            [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
        }
    } failureBlock:^(NSString * _Nonnull description) {
        // 进入DispatchGroup，表示开始一个任务
        
        [weakSelf.tableView.mj_header endRefreshing];
        [weakSelf.tableView.mj_footer endRefreshing];
    }];
}
- (void)onType:(UIButton *)btn {
    NSInteger tag = btn.tag-10;
    [self showPickerView:tag];
    NSLog(@"%ld", (long)btn.tag);
}

- (void)showPickerView:(NSInteger)tag {
    // 准备左侧数据
    NSArray *leftData = @[@"设备状态", @"离线", @"在线"];
    // 创建并显示 picker
    self.pickerView = [[CascadePickerView alloc] initWithLeftData:leftData columns:1];

    if(tag == 1){
        leftData = @[@"设备方向",@"南线",@"北线"];
        self.pickerView = [[CascadePickerView alloc] initWithLeftData:leftData columns:1];

    }else if (tag == 0){
        NSMutableArray * array = [NSMutableArray array];
        NSString* leftV = @"";
        for (NSDictionary * dict in self.systemDictionaryList) {
            [array addObject:dict[@"propertyName"]];
        }
        NSMutableArray * array2 = [NSMutableArray array];
        for (NSDictionary * dict in self.bodyDictionarylist) {
            [array2 addObject:dict[@"propertyName"]];
        }
        if(self.systemDictionaryList.count > 0){
            leftV = self.systemDictionaryList[0][@"propertyName"];
        }
        kWEAK_SELF;
        weakSelf.pickerView = [[CascadePickerView alloc] initWithLeftData:array columns:2];
        weakSelf.pickerView.requestRightDataBlock = ^(NSString *leftValue, void (^completion)(NSArray *rightData)) {
            weakSelf.systemDictionaryId = weakSelf.systemDictionaryList[weakSelf.pickerView.selectedLeftIndex][@"id"];
            [TYNetWorkTool postRequest:TYPostBodyDictionaryList
                            parameters:@{@"levelType":@"巡检",@"systemDictionaryId":weakSelf.systemDictionaryId,@"proId":@"1"}
                          successBlock:^(BOOL success, id  _Nonnull data, NSString * _Nonnull msg) {
                NSArray * arr = data[@"data"];
                NSMutableArray * array2 = [NSMutableArray array];
                for (NSDictionary * dict in arr) {
                    [array2 addObject:dict[@"propertyName"]];
                }
                [weakSelf.pickerView loadRightDataForLeftValue:leftValue withData:array2];

            } failureBlock:^(NSString * _Nonnull description) {
                
            }];
        };
        [weakSelf.pickerView loadRightDataForLeftValue:leftV withData:array2];
      
    }
    
    
    // 设置代理
//    pickerView.delegate = self;
    
    // 或者使用闭包
    kWEAK_SELF;
    weakSelf.pickerView.completionBlock = ^(NSString *leftValue, NSString *rightValue) {
        NSLog(@"%@",[NSString stringWithFormat:@"选择了: %@ - %@", leftValue, rightValue]);
        if(tag == 1){
            weakSelf.direction = leftValue;
            [weakSelf.btn2 setTitle:leftValue forState:UIControlStateNormal];
            if([leftValue isEqualToString: @"设备方向"]){
                weakSelf.direction = @"";
            }
            [weakSelf.tableView.mj_header beginRefreshing];

        }
        if(tag == 2){
            [weakSelf.btn3 setTitle:leftValue forState:UIControlStateNormal];
            weakSelf.onOffStatus = [leftValue isEqualToString:@"离线"]?@"0":@"1";
            if([leftValue isEqualToString: @"设备状态"]){
                weakSelf.onOffStatus = @"";
            }
            [weakSelf.tableView.mj_header beginRefreshing];
            
        }
        if(tag == 0){
            weakSelf.devName = rightValue;
            [weakSelf.btn1 setTitle:rightValue forState:UIControlStateNormal];
            [weakSelf.tableView.mj_header beginRefreshing];
        }
        
    };
    
    [self.pickerView show];
}
#pragma mark ---- UITableViewDelegate, UITableViewDataSource ----
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    return 155;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    YXJCCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[YXJCCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    if (indexPath.row < self.dataArr.count) {
        cell.model =  self.dataArr[indexPath.row];
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    YXJCDetailVC *vc = [[YXJCDetailVC alloc] init];
   YXJCModel * model =  self.dataArr[indexPath.row];
    vc.ID = model.ID;
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark ---- lazy ----
- (TYBaseTableView *)tableView{
    if (!_tableView) {
        _tableView = [[TYBaseTableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor =[UIColor clearColor];
                _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}
@end
